import vlc
import time


class VLCPlayer:
    def __init__(self):
        self.instance = vlc.Instance()
        self.player = self.instance.media_player_new()

    def play_video(self, video_path):
        media = self.instance.media_new(video_path)
        self.player.set_media(media)
        self.player.play()

    def play(self):
        print("播放")
        self.player.play()

    def pause(self):
        print("暂停")
        self.player.pause()

    def stop(self):
        print("停止")
        self.player.stop()

    def forward(self, seconds=5):
        """Fast forward by a specified number of seconds."""
        current_time = self.player.get_time() // 1000  # get_time returns milliseconds
        new_time = min(current_time + seconds, self.player.get_length() // 1000)
        self.player.set_time(new_time * 1000)
        print(f"快进到 {new_time} 秒.")

    def backward(self, seconds=5):
        """Rewind by a specified number of seconds."""
        current_time = self.player.get_time() // 1000
        new_time = max(0, current_time - seconds)
        self.player.set_time(new_time * 1000)
        print(f"后退到 {new_time} 秒.")

    def cmd_control(self):
        help_str = """
暂停: p
播放: s
快进: f
后退: b
音量+: ,
音量-: .
退出:q
请输入指令:"""
        cmd = input(help_str)
        while cmd != "q":
            if cmd == "p":
                self.pause()
            elif cmd == "s":
                self.play()
            elif cmd == "f":
                self.forward()
            elif cmd == "b":
                self.backward()
            else:
                print("无效指令")
            cmd = input(help_str)


if __name__ == "__main__":
    import sys, os

    video_path = "video/234.mp4"
    if len(sys.argv) > 1:
        video_path = sys.argv[1]
    if os.path.exists(video_path):
        print(f"视频路径存在 {video_path}")
    else:
        raise (f"视频路径不存在 {video_path}")
    player = VLCPlayer()
    player.play_video(video_path)
    player.cmd_control()
